<?php
namespace app\admin\controller;

use think\Db;
use think\Request;
use app\admin\model\Category as CategoryModel;
use app\admin\model\DataTable as DataTableModel;
use app\admin\model\TableExtraColumn as TableExtraColumnModel;

/**
 * 一般数据内容   2017-11-15 15:22:57
 * @author huwhis@163.com
 * @version   0.0.1
 */
class DataContent extends Base
{
    public function index($tablename = '')
    {
        $category_model = new CategoryModel();
        $categories = $category_model->field('id, pid, name, tablename')->where('is_del', 0)->select();
        $categories = obj_tree($categories);

        if ($tablename) {
            $pageSize = 20;
            $query = [
                'tablename' => $tablename,
            ];
            $data = Db::table($tablename)->field('id, title, username, clicks, create_time')->order('id', 'desc')->paginate($pageSize, false, ['query'=>$query]);
            $this->assign('data', $data);
            // echo json_encode($data);
            // exit;
        }
        $this->assign('tablename', $tablename);
        $this->assign('categories', $categories);
        return $this->fetch();
    }

    public function addOrEdit($tablename = '', $id = 0)
    {
        if (!$tablename) {
            $this->error('请选择数据表');
        }

        $data_table_model = new DataTableModel();
        $table_id = $data_table_model->where('table_name_en', $tablename)->value('id');

        $table_extra_column_model = new TableExtraColumnModel();
        $table_extra_columns = $table_extra_column_model->where('table_id', $table_id)->field('column_name_en,column_name_cn,note')->select();
        // var_dump($table_extra_columns);
        // exit;

        if ($id) {
            $data = Db::table($tablename)->find($id);
        } else {
            $data = [
                'id' => 0,
                'title' => '',
                'clicks' => 0
            ];
            foreach ($table_extra_columns as $value) {
                $data[$value->column_name_en] = '';
            }
        }
    //    var_dump($data['metallograph_file']);
    //     exit;
        $this->assign('tablename', $tablename);
        $this->assign('table_extra_columns', $table_extra_columns);
        $this->assign('data', $data);
        // 图谱数据
        if ($tablename=='t_metallographic_phase_image' || $tablename=='t_nature_metallograph_image' || $tablename=='t_industry_image') {
            return $this->fetch('addoreditpicturedata');
        } elseif($tablename=='t_knowledge_info' || $tablename=='t_standart_info' || $tablename=='t_document_info' || $tablename=='t_report_info') {
            return $this->fetch('addoreditinfodata');
        }
        return $this->fetch();
    }

    public function doAddOrEdit(Request $request = null)
    {
        $param = $request->param();
        $tablename = $param['tablename'];
        unset($param['tablename']);
        if (!$tablename) {
            $this->error('请选择数据表');
        }
        // var_dump($param);
        // exit;
        if ($request->isPost()) {
            if ($param['title'] == '') {
                $this->error("标题不能为空");
            }

            try {
                if ($param['id'] != 0) {
                    Db::table($tablename)->update($param);
                } else {
                    $param['userid'] = $this->uid;
                    $param['username'] = $this->username;
                    $param['create_time'] = time();
                    unset($param['id']);
                    Db::table($tablename)->insert($param);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:".$msg);
            }
            $this->success('操作成功', 'index?tablename=' . $tablename);
        }
    }

    /**
     * 添加or修改图谱数据
     */
    public function doAddOrEditPicture(Request $request = null)
    {
        if ($request->isPost()) {
            $param = $request->param();
            // var_dump($param);
            // exit;
            $tablename = $param['tablename'];
            unset($param['tablename']);
            if (!$tablename) {
                $this->error('请选择数据表');
            }
            if ($param['title'] == '') {
                $this->error("标题不能为空");
            }
            $metallograph_file = [];
            $delete =  [];
            if (isset($param['delete'])) {
                $delete = $param['delete'];
                unset($param['delete']);
            } 
            for ($i=0; $i <count($param['pic']) ; $i++) {
                if (in_array($i, $delete)) {
                    @unlink(ROOT_PATH.'public' . $param['thumb'][$i]);
                    @unlink(ROOT_PATH.'public' . $param['pic'][$i]);
                } else {
                    $metallograph_file[] = $param['thumb'][$i] . "::::::" . $param['pic'][$i];
                }
            }
            $param['metallograph_file'] = implode(',',$metallograph_file);
            unset($param['thumb']);
            unset($param['pic']);
            // var_dump($param);
            // exit;
            try {
                if ($param['id'] != 0) {
                    Db::table($tablename)->update($param);
                } else {
                    $param['userid'] = $this->uid;
                    $param['username'] = $this->username;
                    $param['create_time'] = time();
                    unset($param['id']);
                    Db::table($tablename)->insert($param);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:".$msg);
            }
            $this->success('操作成功', 'index?tablename=' . $tablename);
        }
    }

    
    /**
     * 添加or修改信息资源
     */
    public function doAddOrEditInfo(Request $request = null)
    {
        if ($request->isPost()) {
            $param = $request->param();
            // var_dump($param);
            // exit;
            $tablename = $param['tablename'];
            unset($param['tablename']);
            if (!$tablename) {
                $this->error('请选择数据表');
            }
            if ($param['title'] == '') {
                $this->error("标题不能为空");
            }
            // 获取表单上传文件
            $file = request()->file('upload_file');
            if($file){
                // $info = $file->validate(['size'=>4194304,'ext'=>'doc,docx,pdf'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'document', '');
                // windows 服务器保存文件时 utf-8 转 GBK
                $saveName = $file->getInfo('name');

                $info = $file->validate(['size'=>4194304,'ext'=>'doc,docx,pdf'])->rule('uniqid')
                    ->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'document', iconv( 'UTF-8', 'GBK', $saveName));
                if($info){
                    // 成功上传后 获取上传信息    
                    // $param['file']= '/uploads/document/' . $info->getSaveName();
                    $param['file']= '/uploads/document/' . $saveName;
                }else{
                    $this->error("错误提示:" . $file->getError());
                }
            }
            try {
                if ($param['id'] != 0) {
                    Db::table($tablename)->update($param);
                } else {
                    $param['userid'] = $this->uid;
                    $param['username'] = $this->username;
                    $param['create_time'] = time();
                    unset($param['id']);
                    Db::table($tablename)->insert($param);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:".$msg);
            }
            $this->success('操作成功', 'index?tablename=' . $tablename);
        }
    }
}
